package de.joergviola.mobj.client.database;

import com.google.gwt.user.client.rpc.AsyncCallback;

public class Barrier<T> {

	private final AsyncCallback<T> outcome;
	private final T result;
	private int incomes;
	private boolean closed;

	public Barrier(AsyncCallback<T> outcome, T result) {
		this.outcome = outcome;
		this.result = result;
		this.incomes = 0;
		this.closed = false;
	}

	public void onFailure(Throwable caught) {
		if (closed)
			return;
		outcome.onFailure(caught);
		closed = true;
	}

	public void enter() {
		if (closed)
			return;
		incomes++;
	}

	public void onSuccess() {
		if (closed)
			return;
		if (--incomes == 0) {
			outcome.onSuccess(result);
			closed = true;
		}
	}

}
